package com.zerui.manager.app.devicegroup.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zerui.cola.dto.Response;
import com.zerui.manager.devicegroup.DeviceGroup;
import com.zerui.manager.devicegroup.domainservice.DeviceGroupRepository;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author wh
 * @create_time 2023-08-23 16:29
 */
@Component
@CatchAndLog
public class DeviceGroupDelCmdExe {

    @Resource
    private DeviceGroupRepository deviceGroupRepository;
    private static final String ROOT_NODE_NAME = "根节点";
    public Response execute(Long id) {
        DeviceGroup deviceGroup = deviceGroupRepository.selectById(id);
        if(ObjectUtils.isEmpty(deviceGroup)){
            throw new BizException("设备分组不存在");
        }
        if(deviceGroup.getOrgName().equals(ROOT_NODE_NAME)){
            throw new BizException("根节点不能删除");
        }
        deviceGroupRepository.deleteById(id);
        Set<String> deviceIds = deviceGroup.getDeviceIds();
        if(CollectionUtils.isNotEmpty(deviceIds)){
            DeviceGroup group = deviceGroupRepository.selectById(deviceGroup.getSupId());
            if (ObjectUtils.isEmpty(group)) {
                throw new BizException("上级分组不存在");
            }
            Set<String> ids = group.getDeviceIds();
            if(CollectionUtils.isEmpty(ids)){
                ids = new HashSet<>();
            }
            ids.addAll(deviceIds);
            deviceGroupRepository.update(group);
        }
        return Response.buildSuccess();
    }

}
